package com.egg.auth.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.egg.auth.model.request.Login;
import com.egg.auth.service.login.ILoginFactory;
import com.egg.basic.enums.sms.SmsTypeEnum;
import com.egg.basic.fegin.BasicSmsFeignClient;
import com.egg.common.core.exception.CustomException;
import com.egg.common.core.model.controller.ApiController;
import com.egg.common.core.model.response.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author east
 */
@Slf4j
@Api(tags = ApiController.API_PREFIX + "账号中心")
@RestController
@RequestMapping("/account")
public class ApiAccountController extends ApiController {


    @Autowired
    private BasicSmsFeignClient basicSmsFeignClient;


    @ApiOperation(value = "通过手机发送注册验证码")
    @GetMapping("/registered/code/phone/let")
    public ResponseData<String> registeredCodeByPhone(
            @ApiParam(value = "手机号码", required = true) @RequestParam(value = "phone") String phone
    ) {
        // 这里通过配置获取到注册的模板及签名，通过基础服务发送验证码
        // 除非供应商参数发生极大变化否则当底层短信商发生变动，只需要修改底层即可，这里无需变动。
        return basicSmsFeignClient.sendSms(phone, SmsTypeEnum.LOGIN);
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login/let")
    public ResponseData<String> login(@RequestBody Login login) {
        Optional<ILoginFactory> proc = ILoginFactory.findFactory(login.getAccountType());
        if (!proc.isPresent()) {
            throw new CustomException("no accountType :" + login.getAccountType());
        }
        return proc.get().login(login);
    }

    @ApiOperation(value = "退出登录")
    @DeleteMapping("/logout/let")
    public ResponseData<String> logout() {
        if (StpUtil.isLogin()) {
            StpUtil.logout();
        }
        return ResponseData.success();
    }


}
